﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MINERP.NewPB.Presenter;
using MINERP.MODEL.FoundationModel;
using DevExpress.XtraEditors.Controls;
using MINERP.MODEL.NewPinBan;
using MINERP.BLL.NewPB;
using System.Threading;

namespace MINERP.NewPB.Forms {
	using DevExpress.XtraEditors;
	
	using MINERP.COM;

	public partial class FrmAutoPinban : XtraForm {
		private SynchronizationContext m_SyncContext;
		public FrmAutoPinban(int userid) {
			UserID = userid;
			InitializeComponent();
			m_SyncContext = SynchronizationContext.Current;
			_AutoPinBanBll = new AutoPB();
			_NewPBBll = new NewPBBLL();
			_AutoPinBanBll.BARCODEWIDTH2 = DataTransfer.BarCodePixWidth;
			_NewPBBll.BARCODEWIDTH = DataTransfer.BarCodePixWidth;
		}
		private int UserID = 1;
		private int MaxOrderInfoNum = 20;
		private decimal ClearWaste;
		private int MinBoardLengthPre = 15;
		private AutoPB _AutoPinBanBll;
		private NewPBBLL _NewPBBll;
		private bool isNeedSmallPic = false;
		private int GetSamllPicCount = 0;
		private List<DisPalyBoardInfo> CurrBoardList = new List<DisPalyBoardInfo>();
		private List<Tb_paperTemplate_Info> listTemp = new List<Tb_paperTemplate_Info>(); //选择的模板
		private bool IsDoing = false;
		private decimal wasteStands = 0;
		private void FrmAutoPinban_Load(object sender, EventArgs e) {
			textEditMaxWaste.Text = IniFile.MaxWaste.ToString();
			txtClearWaste.Text = IniFile.ClearWaste.ToString();
			txtOCCPB.Text = IniFile.OCCPB.ToString();
			txtOCCClearPB.Text = IniFile.OCCClearPB.ToString();
			_AutoPinBanBll.BARCODEWIDTH2 = DataTransfer.BarCodePixWidth;
			_NewPBBll.BARCODEWIDTH = DataTransfer.BarCodePixWidth;
			List<Tb_paperTemplate_Info> TemplateList =
                DataTransfer.TemplateList.Where(p => p.PaperTypeId == DataTransfer.curTemplate.PaperTypeId && p.PaperFaceId == DataTransfer.curTemplate.PaperFaceId).ToList();
			CheckCmbSelectTemplete.Properties.DataSource = TemplateList;
			CheckCmbSelectTemplete.Properties.DisplayMember = "TemplateName";
			CheckCmbSelectTemplete.Properties.ValueMember = "TempLateId";
			//			checkBox1.Checked = timer1.Enabled = Properties.Settings.Default.AutoPinban;
			lbTotalityCellQty.Text = string.Empty;
			lbAvgWaste.Text = string.Empty;
			lbPBPhotoArea.Text = string.Empty;
			lbSurplusArea.Text = string.Empty;
			lbUseCellQty.Text = string.Empty;
			lbSuPhotoCount.Text = string.Empty;
			BangDingUnsure();
			List<DisPalyBoardInfo> listResult = ((List<DisPalyBoardInfo>) gridControlBoard.DataSource).ToList();
			if (listResult.Count > 0) {
				simpleButtonSure.Enabled = true;
			}
			else {
				simpleButtonSure.Enabled = false;
			}
            MaxOrderInfoNum = _AutoPinBanBll.GridQty(DataTransfer.CurPrinter.PrinterID);
			PBINFO();
		}
		private void BangDingUnsure() {
			CurrBoardList = _AutoPinBanBll.GetUnSureBan();
			gridControlBoard.DataSource = CurrBoardList;
		}
		private void ClearBangDingUnsure() {
			CurrBoardList = new List<DisPalyBoardInfo>();
			gridControlBoard.DataSource = CurrBoardList;
		}
		/// <summary>
		/// </summary>
		/// <param name="AvgWaste">平均浪费率</param>
		/// <param name="PBPhotoArea">已拼版照片总面积</param>
		/// <param name="SurplusArea">剩余照片面积</param>
		/// <param name="UseCellQty">已用格子数</param>
		/// <param name="cellTQty">格子总数</param>
		private void PBINFO(decimal AvgWaste, decimal PBPhotoArea, decimal SurplusArea, decimal UseCellQty, int cellTQty, int PBTCellPhotoCount,
							int PBSurplusPhotoCount) {
			m_SyncContext.Send(c => {
				lbTotalityCellQty.Text = cellTQty.ToString();
				lbAvgWaste.Text = AvgWaste.ToString("F2") + "%";
				lbPBPhotoArea.Text = PBPhotoArea.ToString("F2") + "㎡";
				lbSurplusArea.Text = SurplusArea.ToString("F2") + "㎡";
				lbUseCellQty.Text = UseCellQty.ToString();
				lbSuPhotoCount.Text = PBSurplusPhotoCount.ToString();
			}, null);
		}
		private void backgroundWorkerAutoPinBan_DoWork(object sender, DoWorkEventArgs e) {
			//			if (backgroundWorkerAutoPinBan.CancellationPending) {
			//				e.Cancel = true;
			//				IsDoing = false;
			//			}
			//			Tb_paperTemplate_Info outBoardTemplete = new Tb_paperTemplate_Info();
			//			List<PhotoInfo_PinBan> sourceList = new List<PhotoInfo_PinBan>();
			//			while (IsDoing) {
			//				if (backgroundWorkerAutoPinBan.CancellationPending) {
			//					e.Cancel = true;
			//				}
			//				List<PhotoInfo_PinBan> listResult;
			//				decimal outWaste = 0;
			//				int currLength;
			//				DateTime stTime = DateTime.Now;
			//				//获取要拼版的照片在数据库中查找 前20个产品的照片获取规则：1已经拼过的产品2加急产品3开单时间
			//				backgroundWorkerAutoPinBan.ReportProgress(1, "正在获取要拼版的照片");
			//				int currOrderNum = sourceList.GroupBy(g => g.OrderProductId).Count();
			//				int takeNum = (MaxOrderInfoNum - currOrderNum) < 0 ? 0 : (MaxOrderInfoNum - currOrderNum);
			//				//if (isNeedSmallPic)
			//				//{
			//				//    //if (currOrderNum < MaxOrderInfoNum)
			//				//    //{
			//				//    backgroundWorkerAutoPinBan.ReportProgress(5, "正在补充小尺寸照片...");
			//				//    sourceList = _AutoPinBanBll.GetSmallWaitPBPhotoList(DataTransfer.curTemplate, DataTransfer.CurPrinter.PrinterID, takeNum);
			//
			//				//    //}
			//				//}
			//				//else
			//				//{
			//				sourceList = _AutoPinBanBll.GetWaitPBPhotoList(DataTransfer.curTemplate, DataTransfer.CurPrinter.PrinterID, takeNum);
			//				// _NewPBBll.GetAllPhotos(DataTransfer.CurPrinter.PrinterID, 1, 1, DataTransfer.curTemplate.MaterialItemId, false);
			//				//}
			//				isNeedSmallPic = false;
			//				try {
			//					listResult = _AutoPinBanBll.AutoPinSN(sourceList, listTemp, DataTransfer.CurPrinter, out outWaste, out currLength, MinBoardLengthPre, 0,
			//														out outBoardTemplete);
			//				}
			//				catch (Exception ex) {
			//					throw;
			//				}
			//				if ((listResult != null && CheckPhoto(listResult)) || outWaste < 0 || outWaste == 1 || listResult.Count == 0) {
			//					if (listResult != null) {
			//						listResult.ForEach(p => p.IsInBoard = false);
			//					}
			//					IsDoing = false;
			//					backgroundWorkerAutoPinBan.ReportProgress(6, "无照片可用已暂停...");
			//				}
			//				else {
			//					//if (GetSamllPicCount <= 3)
			//					//{
			//					//    //这种情况下要获取小片补空白
			//					//    isNeedSmallPic = true;
			//					//    GetSamllPicCount++;
			//					//}
			//					//else
			//					//{
			//					//    GetSamllPicCount = 0;
			//					//if (GetSamllPicCount ==4)
			//					//{
			//					//    backgroundWorkerAutoPinBan.ReportProgress(4,"");
			//
			//					//    IsDoing = false;
			//					//    break;
			//					//}
			//					//GetSamllPicCount = 0;
			//					int Boardid = _NewPBBll.AutoCreateBoard(listResult, outBoardTemplete, DataTransfer.CurPrinter, UserID, (float) outWaste, currLength);
			//					if (Boardid > 10) //添加成功
			//					{
			//						DisPalyBoardInfo board = new DisPalyBoardInfo();
			//						board.BoardID = Boardid;
			//						board.PhotoNum = listResult.Count();
			//						board.UserfulNum = Math.Round(100 - outWaste*100, 2);
			//						board.Length = (decimal) Math.Round((double) currLength/DataTransfer.CurPrinter.PDPI*2.54, 2);
			//						board.UseTime = (decimal) (DateTime.Now - stTime).TotalSeconds;
			//						board.listPhoto = listResult;
			//						board.FactLength = currLength;
			//						//board.TemplateID = DataTransfer.curTemplateInfo.TemplateId;
			//						board.BoardTemplate = outBoardTemplete;
			//						if (outWaste > wasteStands) {
			//							board.Selected = true;
			//						}
			//						else {
			//							board.Selected = false;
			//						}
			//						CurrBoardList.Add(board);
			//						isNeedSmallPic = false;
			//						backgroundWorkerAutoPinBan.ReportProgress(3, "");
			//						//}
			//						//else
			//						//{
			//						//    //版保存不成功
			//						//}
			//						Thread.Sleep(1200);
			//					}
			//				}
			//			}
		}
		private bool CheckPhoto(List<PhotoInfo_PinBan> inList) {
			int iCount = inList.Count;
			for (int i = 0; i < iCount; i++) {
				for (int j = i + 1; j < iCount; j++) {
					//i j位置进行判断矩形是否重合
					// return true;
					PhotoInfo_PinBan P1 = inList[i];
					PhotoInfo_PinBan P2 = inList[j];
					//两个矩形框的边的一半
					decimal halfP1W = (P1.IsWhirl == true) ? P1.PixFactHeigth/2 : P1.PixFactWidth/2;
					decimal halfP2W = (P2.IsWhirl == true) ? P2.PixFactHeigth/2 : P2.PixFactWidth/2;
					decimal halfP1H = (P1.IsWhirl == true) ? P1.PixFactWidth/2 : P1.PixFactHeigth/2;
					decimal halfP2H = (P2.IsWhirl == true) ? P2.PixFactWidth/2 : P2.PixFactHeigth/2;

					//两个矩形框的中心位置
					decimal c1x = P1.Location.X + halfP1W;
					decimal c1y = P1.Location.Y + halfP1H;
					decimal c2x = P2.Location.X + halfP2W;
					decimal c2y = P2.Location.Y + halfP2H;
					//横向判断
					if (Math.Abs(c1x - c2x) >= halfP1W + halfP2W || Math.Abs(c1y - c2y) >= halfP1H + halfP2H) {
						return false;
					}
					else {
						return true;
					}
				}
			}
			return false;
		}
		private void PostInfo(int flag, string msg) {
			m_SyncContext.Post(c => {
				if (flag == 3) {
					WriteText("保存大板");
					gridControlBoard.DataSource = CurrBoardList;
					gridControlBoard.RefreshDataSource();
					if (checkBoxMark.Checked) {
						MarkBoard();
					}
				}
				else if (flag == 4) {
					//					WriteText("无法找到合适照片，暂停拼版," + timer2.Interval/1000 + "秒后重试");
					//					if (!checkBox1.Checked) {
					//						simpleButtonStartEnd.Text = "开始";
					//					}
				}
				else if (flag == 5) {
					WriteText(msg);
				}
				else if (flag == 6) {
					WriteText(msg);
					//					if (!checkBox1.Checked) {
					//						simpleButtonStartEnd.Text = "开始";
					//						simpleButtonSure.Enabled = true;
					//					}
				}
				else {
					WriteText(msg);
				}
			}, null);
		}
		private void backgroundWorkerAutoPinBan_ProgressChanged(object sender, ProgressChangedEventArgs e) {
			//			if (e.ProgressPercentage == 3) {
			//				WriteText("保存大板");
			//				gridControlBoard.DataSource = CurrBoardList;
			//				gridControlBoard.RefreshDataSource();
			//				if (checkBoxMark.Checked) {
			//					MarkBoard();
			//				}
			//			}
			//			else if (e.ProgressPercentage == 4) {
			//				WriteText("无法找到合适照片，暂停拼版," + timer2.Interval/1000 + "秒后重试");
			//				simpleButtonStartEnd.Text = "开始";
			//			}
			//			else if (e.ProgressPercentage == 5) {
			//				//simpleButtonStartEnd.Text = "停止";
			//
			//				//WriteText("尝试重新拼版");
			//				WriteText((string) e.UserState);
			//			}
			//			else if (e.ProgressPercentage == 6) {
			//				WriteText((string) e.UserState);
			//				simpleButtonStartEnd.Text = "开始";
			//				simpleButtonSure.Enabled = true;
			//			}
		}
		//		private ThreadEx thread;
		private void simpleButton1_Click(object sender, EventArgs e) {
			if (simpleButtonStartEnd.Text == "开始") {
				IniFile.MaxWaste = Convert.ToSingle(textEditMaxWaste.Text);
				IniFile.ClearWaste = Convert.ToSingle(txtClearWaste.Text);
				IniFile.OCCPB = Convert.ToSingle(txtOCCPB.Text);
				IniFile.OCCClearPB = Convert.ToSingle(txtOCCClearPB.Text);
				foreach(CheckedListBoxItem item in CheckCmbSelectTemplete.Properties.Items) {
					if (item.CheckState == CheckState.Checked) {
						listTemp.Add(DataTransfer.TemplateList.FirstOrDefault(p => p.TempLateId == (int) item.Value));
					}
				}
				if (listTemp.Count == 0) {
					return;
				}
                simpleButtonStartEnd.Text = "停止";
                DataTransfer.cancellation.IsStopRequired = false;
				StartPBss();

				WriteText("开始拼版");
			}
			else {
                simpleButtonStartEnd.Text = "开始";
				IsDoing = false;
                DataTransfer.cancellation.IsStopRequired = true;
				//backgroundWorkerAutoPinBan.CancelAsync();
				progressBar1.Value = 0;
				timer1.Enabled = false;
				WriteText("停止拼版");
				progressBar1.Style = ProgressBarStyle.Blocks;
				simpleButtonSure.Enabled = true;
			}
		}
        //private void thread_ThreadExit(ThreadEx sender, object state) {
        //    m_SyncContext.Send(c => {
        //        progressBar1.Style = ProgressBarStyle.Blocks;
        //        simpleButtonStartEnd.Text = "开始";
        //        simpleButtonSure.Enabled = true;
        //        timer1.Enabled = false;
        //        WriteText("停止拼版");
        //    }, null);
        //}
		private void WriteText(string str) {
			richTextBox1.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":  " + str + Environment.NewLine + richTextBox1.Text;
		}
		private int prcessBarVal = 0;
		private void timer1_Tick(object sender, EventArgs e) {
			if (IsDoing) {
				prcessBarVal += 15;
				prcessBarVal = prcessBarVal%100;
				progressBar1.Value = prcessBarVal;
			}
		}
		private void timer2_Tick(object sender, EventArgs e) {
			//			timer2.Enabled = false;
			if (listTemp.Count > 0) {
				if (!IsDoing && true) {
					IsDoing = true;
					if (!backgroundWorkerAutoPinBan.IsBusy) {
						backgroundWorkerAutoPinBan.RunWorkerAsync();
					}
				}
			}
			//			timer2.Enabled = true;
		}
		private void checkBox1_CheckedChanged(object sender, EventArgs e) {
			//			timer2.Enabled = checkBox1.Checked;
			Properties.Settings.Default.AutoPinban = true;
		}
		private void FrmAutoPinban_FormClosing(object sender, FormClosingEventArgs e) {
			//if (IsDoing)
			//{
			//    MessageBox.Show("请先停止，然后退出","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
			//    e.Cancel = false;
			//}
			//			timer2.Enabled = false;
			timer1.Enabled = false;
			IsDoing = false;
			//			if (thread != null && thread.ThreadState == ThreadState.Running) {
			//				thread.Abort();
			//			}
            DataTransfer.cancellation.IsStopRequired = true;
		}
		private void simpleButton1_Click_1(object sender, EventArgs e) {
			if (backgroundWorkerAutoPinBan.IsBusy) {
				backgroundWorkerAutoPinBan.CancelAsync();
			}
			if (IsDoing) {
				MessageBox.Show("请先停止，然后退出", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
			}
			else {
				this.IsDoing = false;
				//backgroundWorkerAutoPinBan.CancelAsync();
				this.Close();
			}
		}
		private void simpleButtonBack_Click(object sender, EventArgs e) {
			List<DisPalyBoardInfo> listResult = ((List<DisPalyBoardInfo>) gridControlBoard.DataSource).Where(p => p.Selected).ToList();
			List<int> BoardIDList = listResult.Select(p => p.BoardID).ToList();
			if (BoardIDList.Count == 0) {
				return;
			}
			int val = _AutoPinBanBll.DeleteBoards(BoardIDList);
			if (val == -1) {
			}
			else {
				//BangdingUnSueBoard();
				//刷新数据
				MessageBox.Show("退版成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
			}
			BangDingUnsure();
		}
		private void linkLabelAll_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
			List<DisPalyBoardInfo> listResult = ((List<DisPalyBoardInfo>) gridControlBoard.DataSource).ToList();
			listResult.ForEach(p => p.Selected = true);
			gridControlBoard.RefreshDataSource();
		}
		private void linkLabelOther_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
			List<DisPalyBoardInfo> listResult = ((List<DisPalyBoardInfo>) gridControlBoard.DataSource).ToList();
			listResult.ForEach(p => p.Selected = !p.Selected);
			gridControlBoard.RefreshDataSource();
		}
		public void MarkBoard() {
			List<DisPalyBoardInfo> listResult = ((List<DisPalyBoardInfo>) gridControlBoard.DataSource).Where(p => p.Selected).ToList();
			List<int> BoardIDList = listResult.Select(p => p.BoardID).ToList();
			if (BoardIDList.Count == 0) {
				//				MessageBox.Show("请先拼版", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
				return;
			}
			int val = _AutoPinBanBll.SaveBoards(BoardIDList);
			if (val == -1) {
			}
			else {
				//BangdingUnSueBoard();
				//刷新数据
				//				MessageBox.Show("退版成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
				ClearBangDingUnsure();
			}
		}
        public void MarkBoard(bool chkSelect)
        {
             chkSelect = true;
			List<DisPalyBoardInfo> listResult = ((List<DisPalyBoardInfo>) gridControlBoard.DataSource).Where(p => p.Selected).ToList();
			List<int> BoardIDList = listResult.Select(p => p.BoardID).ToList();
			if (BoardIDList.Count == 0) {
				//				MessageBox.Show("请先拼版", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
				return;
			}
			int val = _AutoPinBanBll.SaveBoards(BoardIDList);
			if (val == -1) {
			}
			else {
				//BangdingUnSueBoard();
				//刷新数据
				//				MessageBox.Show("退版成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
				ClearBangDingUnsure();
			}
		}
		private void simpleButtonSure_Click(object sender, EventArgs e) {
			MarkBoard();
		}
		private void txtOCCPB_EditValueChanged(object sender, EventArgs e) {
			decimal v1 = Convert.ToDecimal(txtOCCPB.Text);
			decimal v2 = Convert.ToDecimal(txtOCCClearPB.Text);
			//			if (v1 > v2) {
			//				ComControls.Extension.MessageBox.Information("拼版格数不能大于清格格数");
			//				txtOCCPB.Text = ((int) (MaxOrderInfoNum*0.4M)).ToString();
			//			}
		}
		private void txtOCCClearPB_EditValueChanged(object sender, EventArgs e) {
			decimal v1 = Convert.ToDecimal(txtOCCPB.Text);
			decimal v2 = Convert.ToDecimal(txtOCCClearPB.Text);
			//			if (v2 > MaxOrderInfoNum) {
			//				ComControls.Extension.MessageBox.Information("清格数不能小于总格数数");
			//				txtOCCClearPB.Text = ((int) (MaxOrderInfoNum*0.8M)).ToString();
			//			}
		}
	}
}
